package com.tarena.csmall.seckill.checker;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.pojo.seckill.dto.SeckillOrderAddDTO;
import cn.tedu.mall.pojo.seckill.vo.SeckillSpuVO;
import com.alibaba.fastjson.JSON;
import com.tarena.csmall.seckill.service.SeckillSkuService;
import com.tarena.csmall.seckill.service.SeckillSpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

@Component
@Order(200)
public class RandCodeChecker implements SeckillCommitChecker{
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override public void check(SeckillOrderAddDTO dto, String randCode) {
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        //3. 验证 随机码是否正确
        //从redis的预热中,拿到spu的url 截取对比 /seckill/xxxxx
        String spuJson = opsForValue.get(SeckillSpuService.SPU_SECKILL_PREFIX + dto.getSpuId());
        SeckillSpuVO spuVO = JSON.toJavaObject(JSON.parseObject(spuJson), SeckillSpuVO.class);
        if (spuVO==null){
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND,"秒杀预热商品数据不存在");
        }
        String url=spuVO.getUrl();
        //截取 其中的数字 做对比
        String cacheCode = url.substring(9);
        if(!cacheCode.equals(randCode)){
            throw new CoolSharkServiceException(ResponseCode.BAD_REQUEST,"随机码不正确");
        }
    }
}
